<template>
  <view class="navigate-container">
    <!-- 地图区域 -->
    <map
      id="map"
      class="map"
      :latitude="currentLocation.latitude"
      :longitude="currentLocation.longitude"
      :markers="markers"
      :polyline="polyline"
      :scale="16"
      :show-location="true"
      :enable-rotate="true"
      :enable-3D="true"
      :provider="'amap'"
      :amap-key="'8a1e4e4aca95d111e90be19748a0aa17'"
      :amap-sdk-key="'8a1e4e4aca95d111e90be19748a0aa17'"
      :amap-version="'2.0'"
      @tap="handleMapTap"
    ></map>

    <!-- 路线信息卡片 -->
    <view class="route-card" v-if="routeInfo">
      <view class="card-header" @tap="toggleExpand">
        <view class="header-left">
          <text class="title">路线信息</text>
          <view class="distance-info">
            <text class="distance">{{ routeInfo.distance }}米</text>
            <text class="duration">约{{ routeInfo.duration }}分钟</text>
          </view>
        </view>
        <view class="header-right">
          <button class="refresh-btn" @tap.stop="handlePlanRoute">
            <image src="" mode="aspectFit" class="refresh-icon" />
          </button>
          <view class="expand-icon-wrapper">
            <image :src="isExpanded ? '' : ''" mode="aspectFit" class="expand-icon" />
          </view>
        </view>
      </view>

      <scroll-view 
        class="steps-container" 
        :class="{ 'is-expanded': isExpanded }"
        scroll-y="true"
      >
        <view 
          v-for="(step, index) in routeInfo.steps" 
          :key="index"
          class="step-item"
        >
          <view class="step-number">{{ index + 1 }}</view>
          <view class="step-content">
            <text class="step-text">{{ step.instruction }}</text>
            <text class="step-distance">{{ step.distance }}米</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 底部操作栏 -->
    <view class="action-bar">
      <button class="action-btn navigate-btn" @tap="handleStartNavigate">
        <image src="" mode="aspectFit" class="btn-icon" />
        <text>开始导航</text>
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { selectVoByDeviceId } from '@/api/location';
import { planWalkingRoute } from '@/api/map';
import type { DeviceVO } from '@/api/device/types';

// 设备信息
const deviceId = ref(0);
const deviceName = ref('');
const latitude = ref(0);
const longitude = ref(0);

// 地图标记
const markers = ref<any[]>([]);
const polyline = ref<any[]>([]);

// 定义响应式变量
const currentLocation = ref({
    latitude: 28.22778,
    longitude: 112.93886
});

const deviceLocation = ref({
    latitude: 0,
    longitude: 0
});

const routeInfo = ref({
    distance: 0,
    duration: 0,
    steps: []
});

const mapContext = ref<any>(null);

// 添加展开/收起状态
const isExpanded = ref(true);

// 切换展开/收起状态
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value;
};

// 获取当前位置
const getCurrentLocation = () => {
    uni.getLocation({
        type: 'gcj02',
        success: (res) => {
            console.log('获取当前位置成功：', res);
            currentLocation.value = {
                latitude: res.latitude,
                longitude: res.longitude
            };
            // 更新标记点
            updateMarkers();
            // 获取到位置后自动规划路线
            planRoute();
        },
        fail: (err) => {
            console.error('获取当前位置失败：', err);
            uni.showToast({
                title: '获取位置失败',
                icon: 'none'
            });
        }
    });
};

// 更新标记点
const updateMarkers = () => {
    markers.value = [
        {
            id: 1,
            latitude: currentLocation.value.latitude,
            longitude: currentLocation.value.longitude,
            title: '当前位置',
            iconPath: "",
            width: 32,
            height: 32
        }
    ];

    if (deviceLocation.value.latitude && deviceLocation.value.longitude) {
        markers.value.push({
            id: 2,
            latitude: deviceLocation.value.latitude,
            longitude: deviceLocation.value.longitude,
            title: '设备位置',
            iconPath: "",
            width: 32,
            height: 32
        });
    }
};

// 规划路线
const planRoute = async () => {
    try {
        // 确保当前位置和设备位置都存在
        if (!currentLocation.value || !deviceLocation.value) {
            console.error('位置信息不完整：', {
                currentLocation: currentLocation.value,
                deviceLocation: deviceLocation.value
            });
            throw new Error('位置信息不完整');
        }

        console.log('开始规划路线：', {
            from: {
                longitude: currentLocation.value.longitude,
                latitude: currentLocation.value.latitude
            },
            to: {
                longitude: deviceLocation.value.longitude,
                latitude: deviceLocation.value.latitude
            }
        });

        const res = await planWalkingRoute(
            currentLocation.value.longitude,
            currentLocation.value.latitude,
            deviceLocation.value.longitude,
            deviceLocation.value.latitude
        );
        
        console.log('路线规划返回数据：', res);

        if (!res?.data?.steps || !Array.isArray(res.data.steps)) {
            throw new Error('获取路线数据失败');
        }

        // 计算总距离和总时间
        const totalDistance = res.data.steps.reduce((sum, step) => sum + (step.distance || 0), 0);
        // 假设步行速度是 1.4 米/秒，计算总时间（秒）
        const totalDurationSeconds = Math.ceil(totalDistance / 1.4);
        // 转换为分钟
        const totalDurationMinutes = Math.ceil(totalDurationSeconds / 60);

        // 更新路线信息
        routeInfo.value = {
            distance: totalDistance,
            duration: totalDurationMinutes,
            steps: res.data.steps.map(step => ({
                instruction: step.instruction,
                distance: step.distance,
                duration: Math.ceil(step.distance / 1.4 / 60) // 将每个步骤的时间也转换为分钟
            }))
        };

        // 处理路线点
        const allPoints = res.data.steps.reduce((points, step) => {
            if (step.polyline) {
                const stepPoints = step.polyline.split(';').map(point => {
                    const [longitude, latitude] = point.split(',').map(Number);
                    return { longitude, latitude };
                });
                return [...points, ...stepPoints];
            }
            return points;
        }, []);

        // 更新路线
        polyline.value = [{
            points: allPoints,
            color: '#1890ff',
            width: 4,
            dottedLine: false
        }];

        // 调整地图视野以包含整个路线
        if (mapContext.value) {
            mapContext.value.includePoints({
                points: allPoints,
                padding: [50]
            });
        } else {
            // 如果地图上下文不存在，尝试重新获取
            const map = uni.createMapContext('map');
            if (map) {
                mapContext.value = map;
                map.includePoints({
                    points: allPoints,
                    padding: [50]
                });
            }
        }

    } catch (error: any) {
        console.error('规划路线失败：', error);
        uni.showToast({
            title: error.message || '规划路线失败',
            icon: 'none',
            duration: 2000
        });
    }
};

// 页面加载
onLoad(async (options) => {
    if (!options?.id) {
        uni.showToast({
            title: '设备ID不存在',
            icon: 'none'
        });
        setTimeout(() => {
            uni.navigateBack();
        }, 1500);
        return;
    }

    try {
        // 获取设备位置信息
        const res = await selectVoByDeviceId(options.id);
        console.log('设备位置信息：', res);
        
        if (res?.code === 200 && res.data) {
            const deviceData = res.data;
            deviceLocation.value = {
                latitude: deviceData.latitude,
                longitude: deviceData.longitude
            };
            // 更新标记点
            updateMarkers();
            // 获取到设备位置后，获取当前位置并规划路线
            getCurrentLocation();
        } else {
            throw new Error('获取设备位置失败');
        }
    } catch (error: any) {
        console.error('获取设备位置失败：', error);
        uni.showToast({
            title: error.message || '获取设备位置失败',
            icon: 'none'
        });
    }
});

// 点击规划路线按钮时重新获取位置并规划路线
const handlePlanRoute = () => {
    getCurrentLocation();
};

// 开始导航
const handleStartNavigate = () => {
    if (!currentLocation.value || !deviceLocation.value) {
        uni.showToast({
            title: '位置信息不完整',
            icon: 'none'
        });
        return;
    }

    // 打开系统地图进行导航
    uni.openLocation({
        latitude: deviceLocation.value.latitude,
        longitude: deviceLocation.value.longitude,
        scale: 18,
        name: '设备位置',
        address: '设备位置'
    });
};

// 地图点击事件
const handleMapTap = () => {
    // 可以在这里处理地图点击事件
};
</script>

<style lang="scss" scoped>
.navigate-container {
    position: relative;
    width: 100%;
    height: 100vh;
    background-color: #f5f5f5;

    .map {
        width: 100%;
        height: 100%;
    }

    .route-card {
        position: absolute;
        top: 20px;
        left: 20px;
        right: 20px;
        background-color: #fff;
        border-radius: 12px;
        padding: 16px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        max-height: 40vh;
        display: flex;
        flex-direction: column;

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;

            .header-left {
                .title {
                    font-size: 16px;
                    font-weight: bold;
                    color: #333;
                    margin-bottom: 4px;
                }

                .distance-info {
                    display: flex;
                    gap: 12px;

                    .distance, .duration {
                        font-size: 13px;
                        color: #666;
                    }
                }
            }

            .header-right {
                display: flex;
                gap: 8px;
                align-items: center;

                .refresh-btn {
                    width: 32px;
                    height: 32px;
                    padding: 0;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    background: none;
                    border: none;

                    &::after {
                        display: none;
                    }

                    .refresh-icon {
                        width: 20px;
                        height: 20px;
                    }
                }

                .expand-icon-wrapper {
                    width: 32px;
                    height: 32px;
                    display: flex;
                    align-items: center;
                    justify-content: center;

                    .expand-icon {
                        width: 20px;
                        height: 20px;
                        transition: transform 0.3s ease;
                    }
                }
            }
        }

        .steps-container {
            flex: 1;
            overflow-y: auto;
            max-height: 0;
            transition: max-height 0.3s ease-out;

            &.is-expanded {
                max-height: calc(40vh - 80px);
            }

            .step-item {
                display: flex;
                align-items: flex-start;
                padding: 8px 0;
                border-bottom: 1px solid #eee;

                &:last-child {
                    border-bottom: none;
                }

                .step-number {
                    width: 20px;
                    height: 20px;
                    background-color: #1890ff;
                    color: #fff;
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 12px;
                    margin-right: 8px;
                    flex-shrink: 0;
                }

                .step-content {
                    flex: 1;

                    .step-text {
                        font-size: 13px;
                        color: #333;
                        line-height: 1.4;
                        margin-bottom: 2px;
                    }

                    .step-distance {
                        font-size: 12px;
                        color: #999;
                    }
                }
            }
        }
    }

    .action-bar {
        position: absolute;
        bottom: 20px;
        left: 20px;
        right: 20px;
        display: flex;
        justify-content: center;

        .action-btn {
            width: 100%;
            height: 48px;
            border-radius: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            font-weight: bold;
            border: none;

            &.navigate-btn {
                background-color: #1890ff;
                color: #fff;

                .btn-icon {
                    width: 24px;
                    height: 24px;
                    margin-right: 8px;
                }
            }

            &::after {
                display: none;
            }
        }
    }
}
</style> 